<template>
  <Drawer>
    <BaseForm />
  </Drawer>
</template>
<script lang="tsx" setup>
import type { MenuInfoPlain } from '#/api/sys/model/menuModel';

import { useVbenDrawer } from '@vben/common-ui';
import { $t } from '@vben/locales';

import { useVbenForm } from '#/adapter/form';
import { createRole, updateRole } from '#/api/sys/role';
// 定义 emit 类型
interface Emit {
  (e: 'refresh', data?: any): void;
}
// 创建 emit 函数
const emit = defineEmits<Emit>();
const flag = ref(false);

const baseSchema = ref([
  {
    component: 'Input',
    fieldName: 'name',
    label: '商品名称',
  },
  {
    component: 'Input',
    componentProps: {
      clearable: true,
    },
    fieldName: 'sort',
    label: '产品图',
  },
  {
    component: 'Select',
    fieldName: 'type',
    label: '类型',
    defaultValue: '1',
    componentProps: {
      options: [
        {
          label: '高仿',
          value: '1',
        },
        {
          label: 'Super Clone',
          value: '2',
        },
      ],
    },
  },
  {
    component: 'Select',
    fieldName: 'store',
    label: '仓库',
    componentProps: {
      options: [
        {
          label: '香港仓库',
          value: '1',
        },
        {
          label: '英国仓库',
          value: '2',
        },
      ],
    },
  },
  {
    component: 'Input',
    fieldName: 'costPrice',
    label: '成本价',
  },
  {
    component: 'Input',
    fieldName: 'stock',
    label: '库存',
  },
  {
    component: 'Input',
    fieldName: 'remark',
    componentProps: {
      type: 'textarea',
      rows: 4,
      maxlength: 200,
      showWordLimit: true,
    },
    label: '描述',
  },
]);
// 定义表单配置（响应式）
const formConfig = reactive({
  showDefaultActions: false, // 不显示操作按钮
  layout: 'vertical' as const,
  schema: baseSchema.value,
});

// 监听 flag 变化，延迟更新表单配置避免冲突
watch(
  flag,
  (newFlag) => {
    // 使用nextTick和setTimeout确保在下一个事件循环中更新
    nextTick(() => {
      formConfig.schema = newFlag
        ? baseSchema.value.filter((item) => item.fieldName !== 'store')
        : baseSchema.value;
    });
  },
  { immediate: true },
);

const [BaseForm, baseFormApi] = useVbenForm(formConfig);

// 定义弹窗
const [Drawer, drawerApi] = useVbenDrawer({
  // 表单校验
  async onConfirm() {
    // 提交表单
    const { type, id } = drawerApi.getData<Record<string, any>>();
    const isPass = await baseFormApi.validateAndSubmitForm(); // 校验表单
    if (!isPass) {
      return; // 校验不通过
    }
    if (type === 'addData') {
      addOrUpdateRole(isPass);
    }
    if (type === 'editData') {
      addOrUpdateRole(isPass, id);
    }
  },
  // 弹窗打开时触发
  async onOpenChange(isOpen: boolean) {
    if (isOpen) {
      // 设置默认值
      const { type } = drawerApi.getData<Record<string, any>>();
      // 新增打开弹窗时重置表单
      if (type === 'addData') {
        await baseFormApi.resetForm();
        flag.value = false;
      }
      // 编辑打开弹窗时回显数据
      if (type === 'editData') {
        flag.value = true;
        await nextTick();
        await baseFormApi.setValues({
          name: 'Test商品',
          sort: '1024',
          type: '1',
          costPrice: '100',
          stock: '500',
          remark: '这是一个测试商品',
        });
      }
    }
  },
});

/**
 * @author Buke
 * @description 新增或编辑职位
 * @param {MenuInfoPlain} formData - 表单数据对象
 * @param {number} [id] - 职位ID（存在表示编辑，不存在表示新增）
 * @returns {void}
 * @todo 新增倒序排序
 */
async function addOrUpdateRole(
  formData: MenuInfoPlain,
  id?: number,
): Promise<void> {
  const data = {
    ...formData,
    id,
    sort: Number(formData.sort),
    status: Number(formData.status),
  };
  id ? await updateRole(data) : await createRole(data);
  ElMessage.success($t('common.operateSuccess'));
  emit('refresh');
}
</script>
